import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/welcome.vue'
import Users from '../components/user/users.vue'

Vue.use(VueRouter)

const routes = [
  // 自动跳转到login页面
  { path: '/', redirect: '/home' },
  { path: '/login', component: Login },
  { path: '/home',redirect:'/home/welcome', component: Home,children:[
    {path: '/home/welcome', component: Welcome},
    {path:'/home/users', component: Users}
  ] }
]

const router = new VueRouter({
  routes
})
// 挂载路由导航守卫   也就是判断是否有token值
router.beforeEach((to, from, next) => {
  // 如果访问的是登录页面就放行
  if (to.path == '/login') return next()
  // 从sessionStorage中获取保存的数据
  const tokenStr = window.sessionStorage.getItem('token')
  // 判断是否有token，没有返回登录页面
  if (!tokenStr) return next('/login')
  next()
})

export default router
